import cv2
import numpy as np
import math

# 初始化摄像头
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

# 定义监测线位置（距图像顶部的像素数）
scan_line_y = 240  # 应在0-479范围内

def getpos(event,x,y,flags,param):
    if event==cv2.EVENT_LBUTTONDOWN: #定义一个鼠标左键按下去的事件
        print(gray[y,x])
        print((x,y))



while True:
    ret, frame = cap.read()
    if not ret:
        break
    
    # 转换为灰度图（关键步骤）
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
    height, width = gray.shape
    
    # 获取单行灰度值 -------------------------------------------------
    # 方法1：直接获取整行 (返回numpy数组)
    line_data = gray[scan_line_y, :]  # shape=(640,)
    
    # 方法2：获取子区域（当只需部分列时）
    # line_segment = gray[scan_line_y, 100:200]  # 获取100-199列

    plot_canvas = np.zeros((256, width, 3), dtype=np.uint8)
    
    # 绘制波形线
    for x in range(width-1):
        # y1 = line_data[x]    
        # y2 = line_data[x+1]
        y1 = 255 - line_data[x]    # 反转Y轴方向
        y2 = 255 - line_data[x+1]
        cv2.line(plot_canvas, (x,y1), (x+1,y2), (0,255,0), 1)
    
    # 在原图画扫描线
    cv2.line(frame, (0, scan_line_y), (width, scan_line_y), (0,255,255), 1)
    
    # 显示窗口
    cv2.imshow('Camera', frame)
    cv2.imshow('Waveform', plot_canvas)
    cv2.setMouseCallback("Camera",getpos)
    
    if cv2.waitKey(1) == 27:  # ESC退出
        break

cap.release()
cv2.destroyAllWindows()
